import {
  SET_USERNAME,
  SET_PASSWORD,
  SET_IS_REMEMBER_PWD,
  SET_USER_INFO,
  INIT_USER_INFOS,
  SET_LANG,
} from "./actionTypes";
import { CUR_USER_INFOS } from "@/configs/keys";
import { getLocalStorage, setLocalStorage } from "@/libs/utils";
import initialState from "./state";

const mutations = {
  [SET_USERNAME](state, username) {
    state.username = username;

    updateUserStorage("username", username);
  },
  [SET_PASSWORD](state, password) {
    state.password = password;

    updateUserStorage("password", password);
  },
  [SET_IS_REMEMBER_PWD](state, isRememberPwd) {
    state.isRememberPwd = isRememberPwd;

    updateUserStorage("isRememberPwd", isRememberPwd);
  },
  [SET_USER_INFO](state, { key, value }) {
    if (!key) {
      return;
    }
    state.userInfos[key] = value;

    updateUserInfo(key, value);
  },
  [INIT_USER_INFOS](state) {
    Object.getOwnPropertyNames(initialState).forEach((k) => {
      state[k] = initialState[k];
    });
  },
  [SET_LANG](state, lang) {
    state.lang = lang;
    setLocalStorage("lang", lang);
  },
};

function updateUserStorage(key, value) {
  if (!key) {
    return;
  }
  const userLoginInfos = getLocalStorage(CUR_USER_INFOS) || {};
  userLoginInfos[key] = value;
  setLocalStorage(CUR_USER_INFOS, userLoginInfos);
}

function updateUserInfo(key, value) {
  const userLoginInfos = getLocalStorage(CUR_USER_INFOS) || {},
    userInfos = userLoginInfos.userInfos || {};

  userInfos[key] = value;

  userLoginInfos.userInfos = userInfos;
  setLocalStorage(CUR_USER_INFOS, userLoginInfos);
}

export default mutations;
